﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using SMBL.Interface.Document;

namespace SMBL.AFS
{
    /// <summary>
    /// Document Pool
    /// This class is used to control all files.
    /// @Author: Push
    /// </summary>
    public abstract class DocumentPool
    {
        /// <summary>
        /// The main document pool
        /// </summary>
        private static Hashtable myMainDocPool;

        /// <summary>
        /// Get the document provider.
        /// This will check the main document pool to control.
        /// This component is used to syn the file system.
        /// @Author: Push
        /// </summary>
        /// <param name="FilePath">The file path</param>
        /// <returns></returns>
        public static IDocProvider GetDocument(String FilePath)
        {
            // Format the file path
            String tmpPath = formatFilePath(FilePath);

            // Check the pool if the file has been in.
            // If not, add it.
            if (!myMainDocPool.ContainsKey(tmpPath))
            {
                myMainDocPool.Add(tmpPath, false);
            }

            // Lock the document
            while ((Boolean)myMainDocPool[tmpPath]) ;
            myMainDocPool[tmpPath] = true;

            // Return the provider
            return new Providers.Document(tmpPath);
        }

        /// <summary>
        /// Release the document provider
        /// Unlock the file.
        /// @Author: Push
        /// </summary>
        /// <param name="TheProvider"></param>
        public static void ReleaseDocument(IDocProvider TheProvider)
        {
            Providers.Document tmpDoc = (Providers.Document)TheProvider;
            myMainDocPool[tmpDoc.FormatedFilePath] = false;
        }

        /// <summary>
        /// Initialize the file system
        /// @Author: Push
        /// </summary>
        public static void Initialize()
        {
            myMainDocPool = new Hashtable();
        }

        /// <summary>
        /// Terminal the server
        /// Release the resource
        /// @Author: Push
        /// </summary>
        public static void Terminal()
        {
            myMainDocPool.Clear();
        }

        /// <summary>
        /// Format the file path to the unite style
        /// @Author: Push
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        private static String formatFilePath(String FilePath)
        {
            if (FilePath.StartsWith(Global.WebSite.AppPath))
                return FilePath.Substring(Global.WebSite.AppPath.Length);
            if (FilePath.StartsWith("\\") || FilePath.StartsWith("/"))
                return FilePath.Substring(1);
            return FilePath;
        }
    }
}
